package com.bwf.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @Version v1.0
 * @Description: TODO
 * @Author ZHANZHONGXIN
 * @Date 2022/6/9 10:05
 * @Copyright 博为峰
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Class<? extends BaseServlet> aClass = getClass();
        String methodName = req.getParameter("method");
        Method method = null;
        try {
            method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("要调用的方法不存在" + methodName);
        }
        try {
            //方法返回结果
            String result = (String) method.invoke(this, req, resp);
            //结果中的动作
            String action = result.substring(0, result.indexOf(":"));
            //目的地
            String path = result.substring(result.indexOf(":") + 1);
            if (action.equals("forward")) {
                req.getRequestDispatcher(path).forward(req, resp);
            } else if (action.equals("redirect")) {
                resp.sendRedirect(req.getContextPath() + path);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("调用方法出错");
        }
    }
}
